package com.seventh.tickets.service.Impl;

import com.seventh.tickets.base.Result;
import com.seventh.tickets.base.TransResult;
import com.seventh.tickets.entity.User;
import com.seventh.tickets.entity.UserDetail;
import com.seventh.tickets.enums.UserErrorCode;
import com.seventh.tickets.enums.UserStatus;
import com.seventh.tickets.repository.UserDetailRepository;
import com.seventh.tickets.repository.UserRepository;
import com.seventh.tickets.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserService.class);

    private final UserRepository userRepository;
    private final UserDetailRepository userDetailRepository;

    public UserServiceImpl(UserRepository userRepository, UserDetailRepository userDetailRepository) {
        this.userRepository = userRepository;
        this.userDetailRepository = userDetailRepository;
    }

    @Override
    public String userLogin(String userLoginName, String password) {
        User user = userRepository.findByUserLoginName(userLoginName);

        if (user == null) {
            return UserErrorCode.NOT_EXISTS.getCode();
        } else if (user.getUserStatus().toString().equals(UserStatus.IS_LOCKED.getCode())) {
            return UserStatus.IS_LOCKED.getCode();
        } else if (user.getUserStatus().toString().equals(UserStatus.IS_DELETED.getCode())) {
            return UserStatus.IS_DELETED.getCode();
        } else {
            if (user.getUserPassword().equals(password)) {
                user.setLastLoginTime(new Date());
                userRepository.save(user);
                return UserErrorCode.LOGIN_SUCCESS.getCode();
            } else {
                return UserErrorCode.LOGIN_FAILED.getCode();
            }
        }
    }

    @Override
    public User userRegister(String userLoginName, String password) throws Exception {
        User user2 = userRepository.findByUserLoginName(userLoginName);
        if (user2 != null) {
            User user = new User();
            user.setUserLoginName("已存在");
            return user;
        } else {
            User user = new User();
            user.setUserLoginName(userLoginName);
            user.setUserPassword(password);
            user.setUserType(1);
            user.setUserStatus(0);
            user.setRegisterTime(new Date());
            user = userRepository.save(user);
//            System.out.println(user);
            if (user.getUserId() > 0) {
                UserDetail userDetail = new UserDetail();
                userDetail.setUser(user);
                userDetail.setUserLoginName(userLoginName);
                userDetail.setUserName(userLoginName);
                userDetail = userDetailRepository.save(userDetail);
                if (userDetail.getDetailId() <= 0) {
                    throw new Exception("用户详细信息增加失败，用户注册失败");
                } else {
                    return user;
                }
            } else {
                throw new Exception("用户注册失败!");
            }
        }
    }

    /**
     * 修改密码
     *
     * @param userLoginName
     * @param password
     * @param newPassword
     * @return
     * @throws Exception
     */
    @Override
    public Result changePassword(String userLoginName, String password, String newPassword) throws Exception {
        Result result = new TransResult();

        User user = userRepository.findByUserLoginName(userLoginName);

        if (user != null && user.getUserPassword().equals(password)) {
            user.setUserPassword(newPassword);
            user = userRepository.save(user);
            result.setData(user);
        } else {
            result.setErrorCode(UserErrorCode.ORIGIN_PASSWORD_INVALID);
        }

        return result;
    }

    /**
     * 获取用户集合
     *
     * @param keywords
     * @return
     * @throws Exception
     */
    @Override
    public List<User> listUser(String keywords) throws Exception {
        // fixme 增加模糊查询条件

        return userRepository.findAll();
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public User updateUser(User user) throws Exception {
        return userRepository.saveAndFlush(user);
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public User getUser(Long userId) throws Exception {
        return userRepository.getOne(userId);
    }

    /**
     * 获取用户信息
     *
     * @param loginName
     * @return
     * @throws Exception
     */
    @Override
    public User getUser(String loginName) throws Exception {
        return userRepository.findByUserLoginName(loginName);
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public Result deleteUser(Long userId) throws Exception {
        Result result = new TransResult();

        User entity = userRepository.getOne(userId);
        Integer userStatus = Integer.parseInt(UserStatus.IS_DELETED.getCode());

        if (!entity.getUserStatus().equals(userStatus)) {
            entity.setUserStatus(userStatus);
            userRepository.saveAndFlush(entity);
            logger.info(String.format("####%s####====>>>>%s : %s,%s->%s", this.getClass().getSimpleName(), "deleteUser", userId, entity.getUserLoginName(), UserStatus.IS_DELETED));
        }

        result.setData(entity);

        return result;
    }
}
